package com.xnew.utils;

import javax.xml.bind.ValidationException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import org.apache.commons.collections.BidiMap;
//import org.apache.commons.collections.bidimap.TreeBidiMap;

public class StringUtils {

	private static int power[] = { 3, 7, 9, 10, 5, 8, 4, 2 };

	private static String baseCode = "0123456789ABCDEFGHJKLMNPQRTUWXY";

	private static char[] baseCodeArray = baseCode.toCharArray();

	private static int[] wi = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };

	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isNotEmpty(String str) {
		if ((str != null) && !"".equals(str.trim())) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isBlank(String str) {
		int strLen;
		if (str == null || (strLen = str.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if ((Character.isWhitespace(str.charAt(i)) == false)) {
				return false;
			}
		}
		return true;
	}

	public static boolean isNotBlank(String str) {
		return !StringUtils.isBlank(str);
	}

	public static String formatLike(String str) {
		if (isNotEmpty(str)) {
			return "%" + str + "%";
		} else {
			return null;
		}
	}

	public static List<String> filterWhite(List<String> list) {
		List<String> resultList = new ArrayList<String>();
		for (String l : list) {
			if (isNotEmpty(l)) {
				resultList.add(l);
			}
		}
		return resultList;
	}

	/**
	 * 
	 * 判断机构代码是不是有效的
	 *
	 * @return
	 * 
	 */

	public static Boolean isOrgCode(String orgCode) {
		String temp = orgCode.toUpperCase();
		if (temp.contains("-")) {
			temp = temp.replace("-", "");
		}
		if (temp.length() != 9) {
			return false;
		}
		// 获取前面8位
		String pre8 = temp.substring(0, 8);
		char[] pre8chars = pre8.toCharArray();// 0~z;
		// 获取校验码
		String code = temp.substring(8, 9);
		boolean isCode = isCode(code, sum(pre8chars));
		return isCode ? true : false;
	}

	/**
	 * 求和
	 * 
	 * @param bit
	 * @return
	 * 
	 */

	private static int sum(char[] bit) {
		int sum = 0;
		for (int i = 0; i < bit.length; i++) {
			int intTemp = bit[i] > '9' ? (bit[i] - 'A' + 10) : Integer.parseInt(bit[i] + "");
			sum += intTemp * power[i];
		}
		return sum;

	}

	/**
	 * 判断机构代码的校验码和计算出的校验码是否一致
	 * 
	 * @param a
	 * @param b
	 * @return
	 * 
	 */

	private static boolean isCode(String a, int b) {
		String codeTEmp = (11 - b % 11) == 10 ? "X" : (11 - b % 11) == 11 ? 0 + "" : (11 - b % 11) + "";
		return a.equals(codeTEmp);
	}

//	/**
//	 * 
//	 * 生成供较验使用的 Code Map
//	 *
//	 * 
//	 * 
//	 * @return BidiMap
//	 * 
//	 */
//
//	private static BidiMap generateCodes() {
//		BidiMap codes = new TreeBidiMap();
//		for (int i = 0; i < baseCode.length(); i++) {
//			codes.put(baseCodeArray[i], i);
//		}
//		return codes;
//	}
//
//	/**
//	 * 较验社会统一信用代码
//	 *
//	 * @param unifiedCreditCode
//	 *            统一社会信息代码
//	 * @return 符合: true
//	 */
//	@SuppressWarnings("unchecked")
//	public static boolean isCreditCode(String creditCode) {
//		if ((creditCode.equals("")) || creditCode.length() != 18) {
//			return false;
//		}
//		Map<Character, Integer> codes = generateCodes();
//		int parityBit;
//		try {
//			parityBit = getParityBit(creditCode, codes);
//		} catch (ValidationException e) {
//			return false;
//		}
//		return parityBit == codes.get(creditCode.charAt(creditCode.length() - 1));
//	}

	/**
	 * 获取较验码
	 * 
	 * @param unifiedCreditCode
	 *            统一社会信息代码
	 * @param codes
	 *            带有映射关系的国家代码
	 * @return 获取较验位的值
	 * @throws ValidationException 
	 */
	@SuppressWarnings("unused")
	private static int getParityBit(String unifiedCreditCode, Map<Character, Integer> codes) throws ValidationException {
		char[] businessCodeArray = unifiedCreditCode.toCharArray();
		int sum = 0;
		for (int i = 0; i < 17; i++) {
			char key = businessCodeArray[i];
			if (baseCode.indexOf(key) == -1) {
				throw new ValidationException("第" + String.valueOf(i + 1) + "位传入了非法的字符" + key);
			}
			sum += (codes.get(key) * wi[i]);
		}
		int result = 31 - sum % 31;
		return result == 31 ? 0 : result;
	}
	
	/** 将首字母转为大写，其他不变 */
	public static String firstUp(String str) {
		String first = str.substring(0, 1);
		String orther = str.substring(1);
		return first.toUpperCase() + orther;
	}

	/** 将首字母转为小写，其他不变 */
	public static String firstLower(String str) {
		String first = str.substring(0, 1);
		String orther = str.substring(1);
		return first.toLowerCase() + orther;
	}
	
	public static String parseMethod(String methodName){
		if(methodName == null || methodName.trim().length() == 0){
			return null;
		}
		String ret = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
		return ret;
	}

	/**
	 * 对获取的字符串检查是否为空。
	 * @param p_String 一个String。
	 * @return String 如果为空则返回"",如果不为空则返回p_String本身。
	 */
	public static String checkNullString(String p_String){
		if (p_String == null)
			return "";
		else
			return p_String;
	}
	
	/**
	 * 返回 Object 参数的字符串表示形式。
	 * @param p_obj 一个Object。
	 * @return String 如果该对象为null,则返回"";否则返回p_obj.toString()的值。
	 */
	public static String checkNullString(Object p_obj){
		if (p_obj == null)
			return "";
		else
			return p_obj.toString();
	}
	
	/**
	 * 校验邮箱格式
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch(Exception e) {
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 校验手机
	 * @param mobile
	 * @return
	 */
	public static boolean checkMobile(String mobile) {
		boolean flag = false;
		try {
			String check = "\\d{11}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(mobile);
			flag = matcher.matches();
		} catch(Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 校验字符类型的日期
	 * @return
	 */
	public static boolean compareTo(String strDate1,String strDate2) {
		boolean flag = false;
		int i = strDate1.compareTo(strDate2);
			if(i < 0){
				flag = true;
			}
		return flag;
	}
	
	public static void main(String[] args) {
		System.out.println(StringUtils.isOrgCode("633713369ssss"));
//		System.out.println(StringUtils.isCreditCode("91350203MA32LAQK5B"));
	}



	//用分隔符拼接字符串对象
	public  static String JointStrings(Collection<String> strings,String fenge )
	{
		//如果空的就返回空
		if(strings==null || strings.size()==0)
		{
			return  "";
		}

		//拼接字符
		StringBuilder stringBuilder = new StringBuilder();
		int index = 0;
		int size = strings.size();
		for (String s:strings) {
			stringBuilder.append(s);
			//最后一个是不需要拼接的
			if(index < size-1)
			{
				stringBuilder.append(fenge);
			}
			index++;
		}

		return  stringBuilder.toString();
	}
}
